import { asyncRouterMap, constantRouterMap } from '@/router'

function hasPermission(childrenRouter, currentRouters) {
  for (var i = 0; i < currentRouters.length; i++) {
    if (currentRouters[i] === childrenRouter.name) {
      return true
    }
  }
  return false
}

function filterAsyncRouter(asyncRouterMap, currentRouters) {
  var newAsyncRouterMap = asyncRouterMap
  for (var i = 0; i < newAsyncRouterMap.length; i++) {
    var childRoutes = newAsyncRouterMap[i].children ? newAsyncRouterMap[i].children : []
    var childrenRouterList = filterChildRouter(childRoutes, currentRouters)
    if (childrenRouterList.length === 0) {
      newAsyncRouterMap.splice(i, 1)
      i--
    }
  }
  return newAsyncRouterMap
}

// 递归过滤子菜单
function filterChildRouter(routes, currentRouters) {
  if (routes.length > 0) {
    for (var j = 0; j < routes.length; j++) {
      var route = routes[j]
      // 判断是否有子菜单
      var childRoute = routes[j].children ? routes[j].children : []
      if (childRoute.length > 0) {
        filterChildRouter(childRoute, currentRouters)
      } else {
        if (!hasPermission(route, currentRouters)) {
          routes.splice(j, 1)
          j--
        }
      }
    }
  }
  return routes
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    routerNames: [],
    authWords: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    },
    SET_ROUTER_NAMES: (state, routerNames) => {
      state.routerNames = routerNames
    },
    SET_AUTH_WORDS: (state, authWords) => {
      state.authWords = authWords
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        var newAsyncRouterMap = filterAsyncRouter(asyncRouterMap, data)
        commit('SET_ROUTERS', newAsyncRouterMap)
        commit('SET_ROUTER_NAMES', data)
        resolve()
      })
    },
    GenerateAuthWords({ commit }, data) {
      return new Promise(resolve => {
        commit('SET_AUTH_WORDS', data)
        resolve()
      })
    }
  }
}

export default permission
